package com.zsck.pos.activity;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.chinaums.commoncheck.R;
import com.google.gson.Gson;
import com.ums.AppHelper;
import com.zsck.pos.base.BaseTitleActivity;
import com.zsck.pos.bean.LoginResult;
import com.zsck.pos.bean.PosDeviceInfo;
import com.zsck.pos.net.ApiService;
import com.zsck.pos.net.MyObserver;
import com.zsck.pos.net.NetConfig;
import com.zsck.pos.net.RetrofitCilent;
import com.zsck.pos.utils.AESUtils;
import com.zsck.pos.utils.GlideUtils;
import com.zsck.pos.utils.LogUtil;
import com.zsck.pos.utils.SharePreferenceUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.zsck.net.Utils.RxHelper.observableIO2Main;

public class LoginActivity extends BaseTitleActivity implements TextWatcher {


    /*用户名*/
    @BindView(R.id.et_phone)
    EditText mEtPhone;
    /*密码*/
    @BindView(R.id.et_pass)
    EditText mEtPass;
    /*确定*/
    @BindView(R.id.btn_confirm)
    Button mBtnConfirm;
    /*验证码*/
    @BindView(R.id.ll_code)
    LinearLayout mLlCode;
    /*验证码线*/
    @BindView(R.id.view_line)
    View mViewLine;
    /*验证码*/
    @BindView(R.id.et_code)
    EditText mEtCode;
    /*验证码*/
    @BindView(R.id.iv_code)
    ImageView mIvCode;


    private String mUsername;
    private String mPassword;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        initEvents();
        initData();
        String baseSysInfo = AppHelper.getBaseSysInfo(this);
        if (!TextUtils.isEmpty(baseSysInfo)) {
            Gson gson = new Gson();
            PosDeviceInfo posDeviceInfo = gson.fromJson(baseSysInfo, PosDeviceInfo.class);
            LogUtil.e("Login: ", baseSysInfo + "SN:" + posDeviceInfo.getSN());
            SharePreferenceUtils.putString(this, "POSSN", posDeviceInfo.getSN());
        }
//        SharePreferenceUtils.putString(this, "POSSN", "000002040820727525");
    }

    @Override
    public int setLayout() {
        return R.layout.activity_login;
    }

    @Override
    public String setTitle() {
        return "公寓智能收款";
    }

    @Override
    public Activity setActivity() {
        return this;
    }


    private void initEvents() {
        mEtPhone.addTextChangedListener(this);
        mEtPass.addTextChangedListener(this);
        mBtnConfirm.setOnClickListener(this);
        mIvCode.setOnClickListener(this);
    }

    private void initData() {
        mIv_left.setVisibility(View.INVISIBLE);
        if (NetConfig.userInfo != null) {
            Intent intent = new Intent();
            ComponentName componentName = new ComponentName("com.ums.sz.pos", "com.zsck.pos.activity.MainActivity");
            intent.setComponent(componentName);
            startActivity(intent);
            finish();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        mBtnConfirm.setEnabled(!TextUtils.isEmpty(mEtPhone.getText()) && !TextUtils.isEmpty(mEtPass.getText()));
    }

    @Override
    public void afterTextChanged(Editable s) {

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_confirm:
                login();
                break;
            case R.id.iv_code:
                refshCode();
                break;
        }
    }


    private void login() {


        mUsername = mEtPhone.getText().toString();
        mPassword = mEtPass.getText().toString();
        String code = mEtCode.getText().toString();
        if (TextUtils.isEmpty(mUsername)) {
            Toast.makeText(this, "请输入手机号或工号", Toast.LENGTH_LONG).show();
            return;
        }
        if (TextUtils.isEmpty(mPassword)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_LONG).show();
            return;
        }

        Map<String, String> map = new HashMap<>();
        if (mLlCode.getVisibility() == View.VISIBLE) {
            if (TextUtils.isEmpty(code)) {
                Toast.makeText(this, "请输入图形验证码", Toast.LENGTH_LONG).show();
                return;
            }
            map.put("verifyCode", code);
        }

        map.put("accountId", mUsername);
//        map.put("password", mPassword);

        try {
            map.put("password", AESUtils.encrypt( mPassword));
        } catch (Exception e) {
            e.printStackTrace();
        }

        MyObserver<LoginResult> observer = new MyObserver<LoginResult>(this) {
            @Override
            public void onSuccess(LoginResult result) {
                onLogin(result);
            }


            @Override
            public void onFailure(Throwable e, String errorMsg) {
                refshCode();
                LogUtil.e("test", e.getMessage());
                Toast.makeText(LoginActivity.this, "" + errorMsg + e.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void reRequest() {
                login();
            }
        };
    /* RetrofitCilent.getApiService().login(map).
                compose(observableIO2Main(this)).subscribe(observer);*/

        RetrofitCilent.getApiService().loginH5(map).
                compose(observableIO2Main(this)).subscribe(observer);
    }

    private void onLogin(LoginResult result) {
        LogUtil.i("LoginActivity", "登录数据返回");
        if (result == null || result.getData() == null) {
            refshCode();
            LogUtil.i("LoginActivity", "登录错误");
            return;
        }

        if (!result.isState()) {
            LogUtil.i("LoginActivity", "登录失败");
            Toast.makeText(LoginActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
            if (result.getData().getErrorTimes() >= 3) {
                mLlCode.setVisibility(View.VISIBLE);
                mViewLine.setVisibility(View.VISIBLE);
                GlideUtils.display("http://apartmenttest.cmsk1979.com/common-service/app/login/getVerifyCodeImage?accountId=" + mUsername, mIvCode, this);
            }
            return;
        }

        SharePreferenceUtils.putString(this, "username", mUsername);
        SharePreferenceUtils.putString(this, "password", mPassword);

        NetConfig.userInfo = result.getData();
        SharePreferenceUtils.putString(this, "accessToken", NetConfig.userInfo.getAccessToken());
        SharePreferenceUtils.putString(this, "accountId", NetConfig.userInfo.getAccountId());
        SharePreferenceUtils.putString(this, "name", NetConfig.userInfo.getName());
        LogUtil.e("LoginActivity", "开始登录");
        Intent intent = new Intent();
        ComponentName componentName = new ComponentName("com.ums.sz.pos", "com.zsck.pos.activity.MainActivity");
        intent.setComponent(componentName);
        startActivity(intent);
        finish();
    }

    private void refshCode() {
        if (mLlCode.getVisibility() != View.VISIBLE) {
            return;
        }
        GlideUtils.display("http://apartmenttest.cmsk1979.com/common-service/app/login/getVerifyCodeImage?accountId=" + mUsername + "&time=" + System.currentTimeMillis(), mIvCode, this);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            //return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
